//
//  taskListVC.m
//  SQLiteTesting
//
//  Created by kitinat on 1/28/13.
//  Copyright (c) 2013 EGA. All rights reserved.
//

#import "taskListVC.h"

#import "ARC_DB.h"

#import "taskListDetailVC.h"

#import <QuartzCore/QuartzCore.h>

#import "SVPullToRefresh.h"

#import "EGAEmployeeInfo.h"

#import "EGAAppDelegate.h"

#import "EGAUtility.h"


@interface taskListVC ()

@end

@implementation taskListVC


//////////////new
@synthesize arrListNewBook;
@synthesize filteredArrListNewBook;
@synthesize searchBar;
@synthesize isFiltered;
/////////////new



@synthesize tblTaskList;

@synthesize type;

@synthesize lbTitle;

NSArray * arrTask;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    /////new
    //add searchbar delegate
    searchBar.delegate = (id)self;
    /////new
    
    [self dismissKeyboard];
    
    [self setTitleWithType];
    
    [self addPullToRefreshToTable];
    
    
    ARC_DB * DB = [[ARC_DB alloc]init];
    
    if ([DB isHasMyTaskInDB] && ![DB internetConnected])
    {
        [self alertNotConnect];
        [self queryAndSetArr];
        [tblTaskList reloadData];
    }
    else
    {

        [self refresh];
    }
    
    //set infinitescrolling for type 3
    if ([type isEqualToString:@"3"])
    {
        [self setInfiniteScrollingForType3TaskCompleted];
    }
}


#pragma dismisskeyboard
- (void)dismissKeyboard {
    [self globalResignFirstResponder];
}
- (void) globalResignFirstResponder {
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    for (UIView * view in [window subviews]){
        [self globalResignFirstResponderRec:view];
    }
}
- (void) globalResignFirstResponderRec:(UIView*) view {
    if ([view respondsToSelector:@selector(resignFirstResponder)]){
        [view resignFirstResponder];
    }
    for (UIView * subview in [view subviews]){
        [self globalResignFirstResponderRec:subview];
    }
}



//set title with type
-(void)setTitleWithType
{
    if ([type isEqualToString:@"1"])
    {
        lbTitle.text = @"งานของฉัน ที่ยังไม่ดำเนินการ";
    }
    if ([type isEqualToString:@"2"])
    {
        lbTitle.text = @"งานของฉัน ที่อยู่ระหว่างดำเนินการ";
    }
    if ([type isEqualToString:@"3"])
    {
        lbTitle.text = @"งานของฉัน ที่ดำเนินการเรียบร้อย";
    }
}



int myRowNumberType3 = 20;
//set pull to refresh for completed task
-(void)setInfiniteScrollingForType3TaskCompleted
{
    [tblTaskList  addInfiniteScrollingWithActionHandler:^{
        
        int64_t delayInSeconds = 1;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //[tblTaskList beginUpdates];
            
            
            myRowNumberType3 = myRowNumberType3+20;
            NSString * strRowNumber = [NSString stringWithFormat:@"%d",myRowNumberType3];
            
            //NSString *jsonURL=[NSString stringWithFormat:@"http://%@ListMyTaskType3CompletedWithHowManyTopRow.ashx?typeID=0&howManyRow=%@&empID=%@",serviceUrl,strRowNumber,self.appDelegate.employeeInfo.EmpID];
            //NSData *json = [NSData dataWithContentsOfURL:[NSURL URLWithString:jsonURL]];
            
            /////////////////new
            EGAUtility * Util = [[EGAUtility alloc]init];
            NSString *jsonURL=[NSString stringWithFormat:@"ListMyTaskType3CompletedWithHowManyTopRow.ashx&typeID=0&howManyRow=%@&empID=%@",strRowNumber,self.appDelegate.employeeInfo.EmpID];
            NSData *json =[Util getDataFromService:jsonURL];
            /////////////////new

            arrTask = [[NSMutableArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:json options:kNilOptions error:nil]];
            
            
            //[tblTaskList endUpdates];
            [tblTaskList reloadData];
            [tblTaskList.infiniteScrollingView stopAnimating];
        });
    }];
}






-(void)addPullToRefreshToTable
{
    [tblTaskList addPullToRefreshWithActionHandler:^{
        
        int64_t delayInSeconds = 2.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self refresh];
            [tblTaskList.pullToRefreshView stopAnimating];
        });
    }];
    
}


-(void)refresh
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    if([DB internetConnected])
    {
        [DB saveMyTask:self.appDelegate.employeeInfo.EmpID];
        [self queryAndSetArr];
        [tblTaskList reloadData];
    }
    else
    {
        [self alertNotConnect];
    }
}


-(void)queryAndSetArr
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    
    //set type here

    if ([type isEqualToString:@"0"])
        arrTask = [DB getMyTaskType0];
    
    else if ([type isEqualToString:@"1"])
        arrTask = [DB getMyTaskType1];
    
    else if ([type isEqualToString:@"2"])
        arrTask = [DB getMyTaskType2];
    
    else if ([type isEqualToString:@"3"])
        arrTask = [DB getMyTaskType3];
}



//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
//{
//    return [arrTask count];
//}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    if(isFiltered)
    {
        return [filteredArrListNewBook count];
    }
    else
    {
        return [arrTask count];
        
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    // นำ dic ใน array ในแต่ละ row มาโชว์ใน tableview
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    //if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle : UITableViewCellStyleSubtitle
                                  reuseIdentifier : @"Cell"];
    //}
    NSDictionary*dicForEachRow = [arrTask objectAtIndex:indexPath.row];
    
    
    
    ///////new
    
    if(isFiltered)
    {
        dicForEachRow = [filteredArrListNewBook objectAtIndex:indexPath.row];
    }
    else
    {
        dicForEachRow = [arrTask objectAtIndex:indexPath.row];
    }
    
    ///////new
    

    
    
    UILabel *l1=[[UILabel alloc]initWithFrame:CGRectMake(47, 0, 500,60)];
    l1.font = [UIFont systemFontOfSize:20];
    [l1 setTextColor:[UIColor darkGrayColor]];
    l1.text = [NSString stringWithFormat:@"  %@", [dicForEachRow objectForKey:@"Doc_Subject"]];
    [cell.contentView addSubview:l1];

    
    
    
    
    
    
    
    //CommandDate
    NSString * CommandDate = [dicForEachRow objectForKey:@"CommandDate"];
    EGAUtility * Util = [[EGAUtility alloc]init];
    NSString * CommandDateTH = [Util getDateTh:(CommandDate)];
    
    UILabel *lbCommandDateTH=[[UILabel alloc]initWithFrame:CGRectMake(550,9, 120,41)];
    [lbCommandDateTH setTextColor:[UIColor darkGrayColor]];
    lbCommandDateTH.textAlignment = NSTextAlignmentCenter;
    lbCommandDateTH.font = [UIFont systemFontOfSize:17];
    lbCommandDateTH.text = CommandDateTH;
    [cell.contentView addSubview:lbCommandDateTH];
    
    
    
    
    
    
    
    if ([[dicForEachRow objectForKey:@"TaskStatus"] isEqualToString:@"1"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(665, 0, 60,60)];
        UIImage *img = [UIImage imageNamed:@"flag_yellow.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([[dicForEachRow objectForKey:@"TaskStatus"] isEqualToString:@"2"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(665, 0, 60,60)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([[dicForEachRow objectForKey:@"TaskStatus"] isEqualToString:@"3"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(665, 0, 60,60)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([[dicForEachRow objectForKey:@"TaskStatus"] isEqualToString:@"4"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(665, 0, 60,60)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    //set letter_open or letter_close image
    UIImageView *imgLetter=[[UIImageView alloc]initWithFrame:CGRectMake(0,0,41,41)];
    
    ARC_DB * db = [[ARC_DB alloc]init];
    
    BOOL isTaskOpened = [db isHasTaskDetailInDB:[dicForEachRow objectForKey:@"ID"] ];
    
    if ( isTaskOpened == YES )
    {
        imgLetter.image=[UIImage imageNamed:@"letter_open.png"];
    }
    else if ( isTaskOpened == NO )
    {
        imgLetter.image=[UIImage imageNamed:@"letter_close.png"];
    }
    
    cell.imageView.image = imgLetter.image;
    
    
    
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.TLDVC = [[taskListDetailVC alloc] initWithNibName:@"taskListDetailVC" bundle:nil];
    
    //set empid
    self.TLDVC.EmpID = self.appDelegate.employeeInfo.EmpID;
    
    //set docid
    NSDictionary*dicForEachRow = [arrTask objectAtIndex:indexPath.row];
    
    
    //////new
    if(isFiltered)
    {
        dicForEachRow = [filteredArrListNewBook objectAtIndex:indexPath.row];
    }
    else
    {
        dicForEachRow = [arrTask objectAtIndex:indexPath.row];
    }
    
    //////new

    
    self.TLDVC.DocID = [dicForEachRow objectForKey:@"ID"];
    
    [self.view addSubview:self.TLDVC.view];
}



-(EGAAppDelegate*)appDelegate
{
    return  (EGAAppDelegate*)[[UIApplication sharedApplication] delegate];
}





-(void)alertNotConnect
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ไม่สามารถเชื่อมต่อกับเซิฟเวอร์"
                                                    message:@"ทำให้ไม่สามารถอัพเดทข้อมูล"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}





- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc {
   
    [super dealloc];
}


-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
    if(text.length == 0)
    {
        isFiltered = FALSE;
    }
    else
    {
        isFiltered = TRUE;
        filteredArrListNewBook = [[NSMutableArray alloc] init];
        
        for (NSDictionary*dicForEachRow in arrTask)
        {
            //  NSRange rangeFrom = [[dicForEachRow objectForKey:@"Org_Name"] rangeOfString:text options:NSCaseInsensitiveSearch];
            NSRange rangeName = [[dicForEachRow objectForKey:@"Doc_Subject"] rangeOfString:text options:NSCaseInsensitiveSearch];
            //  if(rangeName.location != NSNotFound || rangeFrom.location != NSNotFound)
            if(rangeName.location != NSNotFound)
            {
                [filteredArrListNewBook addObject:dicForEachRow];
            }
        }
    }
    
    [tblTaskList reloadData];
}

@end
